<?php

class ActivityAction extends Action {
	public function getAllActivity() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$ActivityModel = M("activity");
		
		$condition["deleted"] = 0;
		$condition["endTime"] = array(array('exp', 'IS NULL'), array('egt', date("Y-m-d H:i:s")), 'OR');
		$arr = $ActivityModel->alias("activity")->where($condition)
			->field("activity.id, activity.activityName")->select();
		
// 		echo $ActivityModel->getLastSql();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}

	/**
	 * 获取会员等级.
	 */
	public function getMemberLevel($isInterface='false'){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = Session::$user["customerId"];
		$MemberObjectLevelModel = M("member_object_level");
		$MemberObjectModel = M("member_object");
		$result = $MemberObjectModel->field("id")->limit(1)->find();
	    $objectId = $result["id"];
		$condition['objectId']=array('eq',$objectId);
		$condition['deleted']=array('eq',0);
		
		$levelArr = $MemberObjectLevelModel->where($condition)->select();

		if($isInterface == 'true'){
			return $levelArr;
		}else{

			if($levelArr){
				return Output::instance()->objArray($levelArr);
			}else{
				return Output::instance()->resultCode(code_success);
			}
		}
		//return ($isInterface == 'true') ?  : ($levelArr) ? Output::instance()->objArray($levelArr) : Output::instance()->resultCode(code_success);
	}
	
	/**
	 * 获取活动类型
	 */
	public function getActivityType(){
		$retVal = Session::init();
	
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		// ConstDef.php 设置模块关键字
		
		$activType = array();
// 		discount 打折
// 		specialDiscount 限时打折
// 		redEnvelope 红包
// 		voucher 代金卷
// 		integralToCash 积分抵押现金
// 		rewardForGifts 满就送
// 		fortuneWheel 大转盘

		//$activType[0] = array('id' => module_handle_discount, 'name' => '限时促销');
		//$activType[1] = array('id' => module_handle_promotions, 'name' => '限量促销');
        $activType[2] = array('id' => 'wish', 'name' => '心愿单');
//		$activType[1] = array('id' => module_handle_special_discount, 'name' => '限时打折');
// 		$activType[2] = array('id' => module_handle_red_envelope, 'name' => '红包');
// 		$activType[3] = array('id' => module_handle_voucher, 'name' => '代金卷');
// 		$activType[4] = array('id' => module_handle_integral_to_cash, 'name' => '积分抵现金');
// 		$activType[5] = array('id' => module_handle_reward_for_gifts, 'name' => '满就送');
// 		$activType[6] = array('id' => module_handle_fortune_wheel, 'name' => '大转盘');
	
		return ($activType) ? Output::instance()->objArray($activType) : Output::instance()->resultCode(code_success);
	}

	/**
	 * 
	 * 根据模块值获取是否促销活动
	 * 
	 * @param $moduleId 模块值 
	 */
	public function getIsDiscount($moduleId)
    {
        $retVal = Session::init();

        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $isDiscount = 0;

        switch ($moduleId) {
            case 'discount':
                $isDiscount = 1;
                break;

            case 'promotions':
                $isDiscount = 1;
                break;

            default:
                break;
        }

        return $isDiscount;
    }

    /**
     * 修改活动状态
     */
    public function changeActivStatus(){
        $activModel = m('activity');
        $now = date('Y-m-d H:i:s');
        $where['endTime'] = array('ELT', $now);
        $data['deleted'] = 2;
        $activModel->where($where)->save($data);
    }

	/**
	 * 获取活动列表
	 *
	 * @return type json
	 */
	public function getActivityList($activityName='', $isMemberPartake='', $status='', $isDiscount='',  $module='', $discountType='', $startTime='', $endTime='', $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$activModel = m('activity');
        $this->changeActivStatus();
		$cid = Session::$user['customerId'];

		switch ($module){
			case 'discount':
				$where['activ.deleted'] = array('neq', 1);
				$where['activ.module'] = array('exp', 'is not null');
				$where['activ.moduleId'] = array('exp', 'is not null');
				($module != '') ? $where['activ.module'] = $module : '';
				($activityName != '') ? $where['activ.activityName'] = array('like',"%{$activityName}%") : '';
				($discountType != '') ? $where['disc.discountType'] = $discountType : '';
				($isMemberPartake != '') ? $where['activ.isMemberPartake'] = $isMemberPartake : '';
				if($status != ''){
                    if($status != '2'){
                        $where['activ.status'] = $status;
                        $where['activ.endTime'] = array('EGT',date('Y-m-d H:i:s'));
                    }else{
                        $where['activ.endTime'] =  array('ELT',date('Y-m-d H:i:s'));
                    }
                }
				($isDiscount != '') ? $where['activ.isDiscount'] = $isDiscount : '';


                ($startTime != '') ? $where['activ.startTime'] = array('EGT', $startTime) : '';
                if($endTime != ''){

                    if($where['activ.endTime'] != ''){
                        $where['activ.endTime'] = array($where['activ.endTime'],array('ELT', $endTime),'and');
                    }else{
                        $where['activ.endTime'] = array('ELT', $endTime);
                    }
                }


				$arr = $activModel->alias('activ')->join("wx_{$cid}_discount disc On activ.id = disc.activId")->where($where)->limit("{$start},{$limit}")->order("activ.`updateTime` DESC, activ.`createTime` DESC")->field("activ.*, disc.discountType")->select();

                foreach($arr as $k => $v){
                    if($v['endTime'] < date('Y-m-d H:i:s')){
                        $arr[$k]['status'] = 2;
                    }
                }
                if($arr){
                    $count = $activModel->alias('activ')->join("wx_{$cid}_discount disc On activ.id = disc.activId")->where($where)->count();
                    return Output::instance()->objArray($arr, $count);
                }else{
                    return Output::instance()->resultCode(code_success);
                }
				break;

                case 'promotions':
                $where['activ.deleted'] = array('neq', 1);
                $where['activ.module'] = array('exp', 'is not null');
                $where['activ.moduleId'] = array('exp', 'is not null');
                ($module != '') ? $where['activ.module'] = $module : '';
                ($activityName != '') ? $where['activ.activityName'] = array('like',"%{$activityName}%") : '';
                ($discountType != '') ? $where['disc.discountType'] = $discountType : '';
                ($isMemberPartake != '') ? $where['activ.isMemberPartake'] = $isMemberPartake : '';
                if($status != ''){
                    if($status != '2'){
                        $where['activ.status'] = $status;
                        $where['activ.endTime'] = array('EGT',date('Y-m-d H:i:s'));
                    }else{
                        $where['activ.endTime'] =  array('ELT',date('Y-m-d H:i:s'));
                    }
                }
                ($isDiscount != '') ? $where['activ.isDiscount'] = $isDiscount : '';


                ($startTime != '') ? $where['activ.startTime'] = array('EGT', $startTime) : '';
                if($endTime != ''){

                    if($where['activ.endTime'] != ''){
                        $where['activ.endTime'] = array($where['activ.endTime'],array('ELT', $endTime),'and');
                    }else{
                        $where['activ.endTime'] = array('ELT', $endTime);
                    }
                }


                $arr = $activModel->alias('activ')->join("wx_{$cid}_discount disc On activ.id = disc.activId")->where($where)->limit("{$start},{$limit}")->order("activ.`updateTime` DESC, activ.`createTime` DESC")->field("activ.*, disc.discountType")->select();

                foreach($arr as $k => $v){
                    if($v['endTime'] < date('Y-m-d H:i:s')){
                        $arr[$k]['status'] = 2;
                    }
                }
                if($arr){
                    $count = $activModel->alias('activ')->join("wx_{$cid}_discount disc On activ.id = disc.activId")->where($where)->count();
                    return Output::instance()->objArray($arr, $count);
                }else{
                    return Output::instance()->resultCode(code_success);
                }
                break;

                
			default:
				$where['deleted'] = array('neq',1);
				$where['module'] = array('exp', 'is not null');
				$where['moduleId'] = array('exp', 'is not null');
				($module != '') ? $where['module'] = $module : '';
				($activityName != '') ? $where['activityName'] = array('like',"%{$activityName}%") : '';
				($isMemberPartake != '') ? $where['isMemberPartake'] = $isMemberPartake : '';
				($status != '') ? $where['status'] = $status : '';
				($isDiscount != '') ? $where['isDiscount'] = $isDiscount : '';
				($startTime != '') ? $where['startTime'] = array('EGT', $startTime) : '';
				($endTime != '') ? $where['endTime'] = array('ELT', $endTime) : '';
				
				
				$arr = $activModel->alias('activ')->where($where)->limit("{$start},{$limit}")->order("activ.`updateTime` DESC, activ.`createTime` DESC")->select();
                if($arr){
                    $count = $activModel->where($where)->count();
                    return Output::instance()->objArray($arr, $count);
                }else{
                    return Output::instance()->resultCode(code_success);
                }
				break;
		}
	}
	
	/**
	 * 根据ID获取活动
	 * @param int $id 活动id
	 */
	public function getActivityById($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$ActivityModel = M("activity");
	
		$condition["id"] = array("eq",$id);
		$activity = $ActivityModel->where($condition)->find();
		if ($activity) {
			Output::instance()->object($activity);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	/**
	 * 添加活动
	 */
	public function addActivity($activityName, $startTime, $endTime, $isMemberPartake, $status, $module){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$activModel = m('activity');
		$now = date('Y-m-d H:i:s');
		$data['activityName'] = $activityName;
		$data['createTime'] = $now;
		$data['startTime'] = $startTime;
		$data['endTime'] = $endTime;
        $data['updateTime'] = $now;
		$data['isMemberPartake'] = $isMemberPartake;
		$data['status'] = $status;
		$data['module'] = $module;
		$data['isDiscount'] = $this->getIsDiscount($module);
		
		$result = $activModel->add($data);
		
		if ($result) {
			$data["id"] = $result;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	/**
	 * 
	 * 修改活动
	 * 
	 * @param int $id 活动ID
	 * @param string $activityName 活动名称
	 * @param string $module 模块值
	 * @param string $moduleId 模块ID
	 * @param string $startTime 开始时间
	 * @param string $endTime 结束时间
	 * @param string $accessTag 访问标签
	 * @param string $isMemberPartake 是否仅限会员参加
	 * @param string $partTakeMemberLevel 会员等级
	 * @param string $memo 备注
	 */
	public function updateActivity($id,$activityName, $module, $moduleId = NULL, $status=0, $startTime = NULL,$endTime = NULL,$accessTag = NULL,
			$isMemberPartake = NULL,$partTakeMemberLevel = NULL,$memo = NULL)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $ActivityModel = M("activity");

        $time = date("Y-m-d H:i:s");
        $data["activityName"] = $activityName;
        $data["module"] = $module;
        $data["startTime"] = $startTime;
        $data["endTime"] = $endTime;
        $data["accessTag"] = $accessTag;
        $data["isMemberPartake"] = $isMemberPartake;
        $data["partTakeMemberLevel"] = $partTakeMemberLevel;
        $data["updateTime"] = $time;
        $data["memo"] = $memo;
        $data['status'] = $status;

        if($endTime > $time) {
            $data['deleted'] = 0;
        }else{
            $data['deleted'] = 2;
        }

        $this->delDiscountPrice($id, $isMemberPartake, $module);
        $result = $ActivityModel->where("id=$id")->save($data);
        if ($result !== false) {
            $data["id"] = $id;
            Output::instance()->object($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 修改活动的时候检查如果是限时促销并且修改了是否仅限会员参加的时候, 将清空所有折扣商品的价格按原价卖,
     * @param $id 活动ID
     * @param $isMemberPartake 是否仅限会员（修改时候的值）
     * @param $module 模块
     */
    public function delDiscountPrice($id, $isMemberPartake, $module){

        if($module == "discount"){
            $activModel = m('activity');
            $oldIsMember = $activModel->where("`id`={$id}")->getField("isMemberPartake");

            #如果修改了则清空该限时促销活动中的所有商品的价格.
            if($oldIsMember != $isMemberPartake){
                $discModel = m('discount');
                $discProdModel = m('discount_product');
                $discountId = $discModel->where("`activId` = {$id} And `deleted` = 0")->getField("id");

                $update['discountNum'] = NULL;
                $update['discountPrice'] = NULL;
                $discModel->where("`activId` = {$id} And `deleted` = 0 ")->save($update);
//                Log::write($discModel->getLastSql());
                $discProdModel->where("`discountId` = {$discountId} And `deleted` = 0")->save($update);
            }
        }

        if($module == "promotions"){
            $activModel = m('activity');
            $oldIsMember = $activModel->where("`id`={$id}")->getField("isMemberPartake");

            #如果修改了则清空该限量促销活动中的所有商品的价格.
            if($oldIsMember != $isMemberPartake){
                $discModel = m('discount');
                $discProdModel = m('discount_product');
                $discountId = $discModel->where("`activId` = {$id} And `deleted` = 0")->getField("id");

                $update['discountNum'] = NULL;
                $update['discountPrice'] = NULL;
                $update['count'] = NULL;
                $update['personalNum'] = NULL;
                $discModel->where("`activId` = {$id} And `deleted` = 0 ")->save($update);
//                Log::write($discModel->getLastSql());
                $discProdModel->where("`discountId` = {$discountId} And `deleted` = 0")->save($update);
            }
        }
    }

    /**
     * 根据ID删除指定活动.
     * @param $id
     */
    public function delActivityById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $ActivityModel = M("activity");
        $where['id'] = $id;
        $activity = $ActivityModel->where($where)->find();
        $delData['deleted'] = 1;
        $ActivityModel->where($where)->save($delData);
        $module = $activity['module'];
        $moduleId = $activity['moduleId'];
        $result = $this->delActivityModel($module, $moduleId);

        if($result && $activity){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     *
     * 删除活动时 同步删除对应的具体模块。
     *
     * @param $module 模块名
     * @param $moduleId 模块ID
     * @return bool 是否执行成功
     */
    public function delActivityModel($module, $moduleId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        if($module == "discount"){
            $Module = m('discount');
            $where['id'] = $moduleId;
            $delData['deleted'] = 1;
            $result = $Module->where($where)->save($delData);

            $discProd = m('discount_product');
            $disproWhere['discountId'] =  $moduleId;
            $result1 = $discProd->where($disproWhere)->save($delData);

            return ($result && $result1) ? true : false;
        }
        if($module == "wish"){
            $Module = m('wish_act');
            $where['id'] = $moduleId;
            $delData['deleted'] = 1;
            $result = $Module->where($where)->save($delData);
            
            return ($result && $result1) ? true : false;
        }
    }

    /**
     * 检查活动名称是否可用
     *
     * @param String $activityName 活动名称
     * @return bool true,可以 false,已存在
     */
    public function checkActivityName($activityName, $id=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $activityModel = m('activity');
        $where['activityName'] = $activityName;
        $where['deleted'] = array('neq',1);
        $where['moduleId'] = array('neq', '');
        if($id != null) $where['id'] = array('neq', $id);
        $result = $activityModel->where($where)->count();
        Output::instance()->object(intval($result));
    }


}